const express = require("express");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const mysqlStore = require("express-mysql-session")(session);
const mysql2 = require("mysql2");
const md5 = require("md5");
const app = express();

const getDBConfig = () => ({
  host: "127.0.0.1",
  port: 3306,
  user: "root",
  password: "root",
  // 数据库名
  database: "test",
  // 创建连接池数量
  connectionLimit: 1,
});
// 创建连接池
const config = getDBConfig();
const promisePool = mysql2.createPool(config).promise();
const sessionStore = new mysqlStore(config); //  创建session存储到mysql数据库中
app
  .use(express.json())
  .use(express.urlencoded({ extended: false }))
  .use(cookieParser())
  .use(
    session({
      name: "sid", // 设置 cookie 中保存 session id 的字段名称
      secret: "keyboard cat", // 通过设置 secret 来计算 hash 值并放在 cookie 中，使产生的 signedCookie 防篡改
      saveUninitialized: false, // 是否自动保存未初始化的会话，建议false
      resave: false, // 是否每次都重新保存会话，建议false
      store: sessionStore, // 将session存储到mysql数据库中
      //  cookie的相关设置
      cookie: {
        httpOnly: true, // 开启后前端无法通过 JS 操作cookie
        maxAge: 1000 * 60 * 60, // 设置session的有效时间，单位毫秒
      },
    })
  );
// 注册接口
app.post("/register", async (req, res) => {
  const { userName, password } = req.body;
  // 插入数据
  //   await promisePool.query("insert into User set ?", {
  //     userName,
  //     password: md5(password),
  //   });
  await promisePool.query("insert into User (userName, password) values(?,?)", [
    userName,
    md5(password),
  ]);
  res.send({
    code: 200,
    msg: "注册成功！",
  });
});
// 登录接口
app.post("/login", async (req, res) => {
  const { userName, password } = req.body;
  // 查询数据
  const [user] = await promisePool.query(
    "select * from User where userName = ? and password = ?",
    [userName, md5(password)]
  );
  if (user.length > 0) {
    // 写入session
    req.session.userName = user[0].userName;
    res.send({
      code: 200,
      msg: "登录成功！",
    });
  } else {
    res.send({
      code: 403,
      msg: "登录失败！",
    });
  }
});
app.listen(3000, () => {
  console.log("启动成功！");
});
